package com.lanyu.community.api.service.impl;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.lanyu.mybatis.dao.entity.*;
import com.lanyu.mybatis.dao.mapperex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanyu.community.api.beans.ZanlistParams;
import com.lanyu.community.api.constat.CommonConstant;
import com.lanyu.community.api.service.ICommunityDynamicService;
import com.lanyu.community.api.service.ISysUserService;
import com.lanyu.community.api.util.GsonUtil;
import com.lanyu.community.api.util.RedisUtil;
import com.lanyu.community.api.util.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  动态服务实现类
 * </p>
 *	 return page.setRecords(sysAnnouncementMapper.querySysCementListByUserId(page, userId, msgCategory));
 * @Author: suibin
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class CommunityDynamicServiceImpl extends ServiceImpl<CommunityDynamicsMapper, CommunityUserDynamics> implements ICommunityDynamicService {

	@Autowired
	private CommunityDynamicsMapper communityDynamicsMapper;
	
	@Autowired
	private CommunityUserFollowsMapper communityUserFollowsMapper;

	@Autowired
	private CommunityUserDiscussMapper communityUserDiscussMapper;

	@Autowired
	private UcenterUserinfoPlusMapper ucenterUserinfoPlusMapper;

	@Autowired
	private CommunityUserChatMapper communityUserChatMapper;

	@Autowired
	@Lazy
	private RedisUtil redisUtil;
	
	@Autowired
	private CommunityUserZanlistMapper communityUserZanlistMapper;

	//地区范围内7天首页推荐，缓存10秒dongtaiHomeCache。
	@Cacheable(value = "dynamics:home_latestweek_cache",key = "'params_'+#page.getCurrent()+#m")
	@Override
	public Page<CommunityUserDynamics> getCommunityDynamicsLatestweek(Page<CommunityUserDynamics> page,
			Map<String,Object> m) {
		//Map<String,Object> m = new HashMap<>();
		//m.put("id",5);
		// TODO Auto-generated method stub
		return page.setRecords(communityDynamicsMapper.queryCommuntiyListByWeek(page, m));
	}

	//实时的办法，发布动态时候，查询相关关注UID，分发给各个用户的APP小红点。
	//APP判断有红点时，删除缓存并下拉。

	//7天关注的动态,每个用户1分钟缓存一次数据。
	@Cacheable(value = "dynamics:guanzhu_latestweek_cache",key = "'params_'+#page.getCurrent()+#m")
	@Override
	public Page<CommunityUserDynamics> getCommunityGuanzhuDynamicsLatestweek(Page<CommunityUserDynamics> page, Map<String, Object> m) {
		return page.setRecords(communityDynamicsMapper.queryCommuntiyListByGuanzhuWeek(page, m));
	}

	@Override
	public String publishChat(CommunityUserChat cuc) {
		//发布动态
		CommunityUserChat cuc1=new CommunityUserChat();
		cuc1.setCreateTime(cuc.getCreateTime());
		cuc1.setFromUid(cuc.getFromUid());
		cuc1.setToUid(cuc.getToUid());
		cuc1.setMessage(cuc.getMessage());
		cuc1.setType(cuc.getType());
		int ret=communityUserChatMapper.insert(cuc1);
		return cuc1.getChatId()+"";
	}

	//@Cacheable(value = "chat:message_cache",key = "'params_'+#page.getCurrent()+#m")
	@Override
	public Page<CommunityUserChat> getCommunityChatList(Page<CommunityUserChat> page, Map<String, Object> m) {

		return page.setRecords(communityUserChatMapper.queryCommuntiyUserChatByParams(page, m));
	}

	@Override
	public Page<CommunityUserChat> getCommunityChatPersonList(Page<CommunityUserChat> page, Map<String, Object> m) {
		return page.setRecords(communityUserChatMapper.queryCommuntiyUserChatPersonByParams(page, m));
	}

	@Override
	@Transactional
	public int upzan(String uid, String did) {
		
		int ok=communityUserZanlistMapper.upzan(did);
		if(ok>0) {
			CommunityUserZanlist cuz=new CommunityUserZanlist ();
			cuz.setCreateTime(new Date());
			cuz.setDid(did);
			cuz.setZanUid(uid);
			ok=communityUserZanlistMapper.insert(cuz);
		}
		return ok;
	}
	//动态多少人点赞列表，可以缓存1分钟更新
	@Cacheable(value = "zan:zanlist_cache",key = "'params_'+#page.getCurrent()+#did")
	@Override
	public Page<ZanlistParams> getZanlist(Page<ZanlistParams> page, String did) {
		// TODO Auto-generated method stub
		return page.setRecords(communityUserZanlistMapper.getzan_list(page,did));
	}
	@Override
	public String publishDt(CommunityUserDynamics cud) {
		//发布动态
		CommunityUserDynamics dud=new CommunityUserDynamics();
		
		dud.setdTitle(cud.getdTitle());
		dud.setdMessage(cud.getdMessage());
		dud.setdIsdel(0);
		dud.setUid(cud.getUid());
		dud.setdType(cud.getdType());
		dud.setdPosttime(new Date());
		dud.setLocation(cud.getLocation());
		dud.setdUrl(cud.getdUrl());
		int ret=communityDynamicsMapper.insert(dud);
		
		return dud.getDid()+"";
	}

	@Override
	public UcenterUserinfo getUserinfo(String uid) {
		Wrapper<UcenterUserinfo> wrapperq=new QueryWrapper<UcenterUserinfo>()
				.eq("uid",uid)
				;
		return ucenterUserinfoPlusMapper.selectOne(wrapperq);
	}

	@Override
	public Page<CommunityUserDynamics> getCommunityDynamicsByParams(Page<CommunityUserDynamics> page,
			Map<String, Object> m) {
		// TODO Auto-generated method stub
		return page.setRecords(communityDynamicsMapper.queryCommuntiyListByParams(page, m));
	}

	@Override
	public int delDiscuss(String discId,String uid) {

		Wrapper<CommunityUserDiscuss> wrapperq=new QueryWrapper<CommunityUserDiscuss>()
				.eq("disc_id", discId).eq("disc_uid",uid)
				;
		CommunityUserDiscuss c=communityUserDiscussMapper.selectOne(wrapperq);
		if(c!=null){
			Wrapper<CommunityUserDiscuss> wrapper=new QueryWrapper<CommunityUserDiscuss>()
					.eq("disc_id", discId)
					;
			return communityUserDiscussMapper.delete(wrapper);
		}
		return 0;
	}

	@Override
	public String addDiscuss(CommunityUserDiscuss cud) {
		communityUserDiscussMapper.insert(cud);

		//动态评论数+1
		String discid=cud.getDiscId();
		if(discid!=""){
			communityDynamicsMapper.updiscount(cud.getDiscDid());
		}
		return discid;
	}

	//评论列表实时，不缓存
	//@Cacheable(value = "discuss:discusslist_cache",key = "'params_'+#page.getCurrent()+#m")
	@Override
	public Page<CommunityUserDiscuss> getDiscussList(Page<CommunityUserDiscuss> page, Map<String,Object> m) {
		return page.setRecords(communityUserDiscussMapper.queryCommuntiyUserDiscussByParams(page,m));
	}

	@Override
	public int delDt(String uid, String did) {
		// TODO Auto-generated method stub
		//删除redis 动态
		//redisUtil.del("dongtai:mydongtai_home_"+uid);
		//删除mysql 动态
		Wrapper<CommunityUserDynamics> wrapper=new QueryWrapper<CommunityUserDynamics>()
				.eq("uid", uid).eq("did", did)
				;
		return communityDynamicsMapper.delete(wrapper);
	}

    @Override
    public int delChat(String chat_id) {
        Wrapper<CommunityUserChat> wrapper=new QueryWrapper<CommunityUserChat>()
                .eq("chat_id", chat_id)
                ;
        return communityUserChatMapper.delete(wrapper);

    }

    @Override
	public int follow(String from_uid, String to_uid) {
		// TODO Auto-generated method stub
		CommunityUserFollows entity =new CommunityUserFollows();
		entity.setFromUid(from_uid);
		entity.setToUid(to_uid);
		entity.setCreateTime(new Date());
		entity.setRelType(0);
		int x= communityUserFollowsMapper.insert(entity);//mysql 作为记录，当关注量10万多时候查询，数据量大数据库压力大
		//if(x>0) {
			//查询用户信息
			Wrapper<UcenterUserinfo> wrapper=new QueryWrapper<UcenterUserinfo>()
					.eq("uid", to_uid)
					;
			UcenterUserinfo one=ucenterUserinfoPlusMapper.selectOne(wrapper);
			long timeStamp = System.currentTimeMillis();//获取当前时间戳(这是毫秒时间戳)
			//插入到zset,查询的时候走redis
			redisUtil.zAdd("follow:follow_guanzhu_"+from_uid, to_uid, timeStamp);//发送到我的关注zset
			String tojson=GsonUtil.GsonString(one);
			redisUtil.hset("user:users_baseinfo", to_uid, tojson);
			
			//定时任务。从数据库查询from_uid的粉丝。插入。假如该用户有10万粉丝，
			//redisUtil.zAdd("follow:follow_fensi_"+from_uid, tojson, timeStamp);//发送到我的粉丝zset
		//}

		return x;
		
	}

	@Override
	public int unfollow(String from_uid, String to_uid) {
		// TODO Auto-generated method stub

		Wrapper<CommunityUserFollows> wrapper=new QueryWrapper<CommunityUserFollows>()
				.eq("from_uid", from_uid).eq("to_uid", to_uid)
				;
		int x=communityUserFollowsMapper.delete(wrapper);
		if(x>0) {
			redisUtil.zRemove("follow:follow_guanzhu_"+from_uid, to_uid);
			redisUtil.hdel("user:users_baseinfo", to_uid);
		}
		return x;
	}

	@Override
	public Page<UcenterUserinfo> getFollowUserinfos(Page<UcenterUserinfo> page, String uid) {
		// TODO Auto-generated method stub
		
		return null;
	}
	//缓存到redis里，分页的粉丝列表
	@Cacheable(value = "fensi:fensilist_cache",key = "'params_'+#page.getCurrent()+#m")
	@Override
	public Page<UcenterUserinfo> getFensiUserinfos(Page<UcenterUserinfo> page,Map<String, Object> m) {
		// TODO Auto-generated method stub
		//System.out.print("--------------------:"+page.getCurrent());
		return page.setRecords(communityUserFollowsMapper.queryCommuntiyUserFollowsByParams(page,m));
		
	}
	
}
